package softtech.apps.customadapter;

import java.util.List;

import softtech.apps.autoanswerphonecall.DialogAddSms;
import softtech.apps.autoanswerphonecall.MainActivity;
import softtech.apps.autoanswerphonecall.R;
import softtech.apps.model.Config;
import softtech.apps.model.DatabaseHandler;
import softtech.apps.model.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

public class ItemSmsAdapter extends BaseAdapter {

	private Context mContext;

	private Activity mActivity;

	private List<Message> listMsg;

	private DatabaseHandler dbHandler;

	private int mSelectedPosition = -1;

	private RadioButton mSelectedRB;

	private boolean mIsCheck = false;

	public ItemSmsAdapter(Activity activity) {

		mActivity = activity;
		mContext = activity.getApplicationContext();

		dbHandler = new DatabaseHandler(mContext);

		listMsg = dbHandler.getAllMessage();

		getMessageDefault();

	}

	private void getMessageDefault() {
		int size = listMsg.size();

		for (int i = 0; i < size; i++) {
			if (listMsg.get(i).get_isDefault() == dbHandler.VALUE_IS_DEFAULT) {
				mSelectedPosition = i;
			}
		}
	}

	/**
	 * update list message
	 */
	public void updateListMessage() {

		listMsg = dbHandler.getAllMessage();
		
		getMessageDefault();

		notifyDataSetChanged();
		
		((MainActivity) mActivity).setRowDisplay(mSelectedPosition);

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listMsg.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return listMsg.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		ViewHolder viewHolder = null;

		if (convertView == null) {

			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			convertView = inflater.inflate(R.layout.item_answer_by_sms, null);

			viewHolder = new ViewHolder();

			viewHolder.rad_sms_default = (RadioButton) convertView
					.findViewById(R.id.bt_item_sms);

			viewHolder.tv_content = (TextView) convertView
					.findViewById(R.id.tv_item_sms_content);

			viewHolder.tv_content.setTypeface(null, Typeface.BOLD);

			viewHolder.tv_title = (TextView) convertView
					.findViewById(R.id.tv_item_sms_title);

			viewHolder.tv_title.setTypeface(null, Typeface.BOLD);

			viewHolder.bt_delete = (ImageButton) convertView
					.findViewById(R.id.bt_item_sms_delete);

			viewHolder.ll_item_sms = (LinearLayout) convertView
					.findViewById(R.id.ll_item_sms);

			convertView.setTag(viewHolder);

		} else {

			viewHolder = (ViewHolder) convertView.getTag();
		}

		mSelectedRB = viewHolder.rad_sms_default;

		// set default sms reply
		viewHolder.rad_sms_default.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mSelectedPosition != position && mSelectedRB != null) {
					mSelectedRB.setChecked(false);

					listMsg.get(mSelectedPosition).set_isDefault(dbHandler.VALUE_NON_DEFAULT);

					dbHandler.updateMessage(listMsg.get(mSelectedPosition));

					mSelectedPosition = position;

					mSelectedRB = (RadioButton) v;

					listMsg.get(position).set_isDefault(dbHandler.VALUE_IS_DEFAULT);

					dbHandler.updateMessage(listMsg.get(position));

					notifyDataSetChanged();

					((MainActivity) mActivity).updateSmsSub();
				}

			}
		});

		if (mSelectedPosition != position) {

			mSelectedRB.setChecked(false);
		} else {

			mSelectedRB.setChecked(true);

			if (mSelectedRB != null
					&& viewHolder.rad_sms_default != mSelectedRB) {
				mSelectedRB = viewHolder.rad_sms_default;
			}
		}

		// edit sms
		viewHolder.ll_item_sms.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, DialogAddSms.class);
				intent.putExtra("requestCode",
						MainActivity.REQUEST_CODE_DIALOG_EDIT_SMS);

				intent.putExtra(DatabaseHandler.MSG_KEY_ID,
						listMsg.get(position).get_id());

				intent.putExtra(DatabaseHandler.MSG_KEY_TITLE,
						listMsg.get(position).get_title());

				intent.putExtra(DatabaseHandler.MSG_KEY_CONTENT,
						listMsg.get(position).get_content());

				intent.putExtra(DatabaseHandler.MSG_KEY_DEFAULT,
						listMsg.get(position).get_isDefault());

				mActivity.startActivityForResult(intent,
						MainActivity.REQUEST_CODE_DIALOG_EDIT_SMS);
			}
		});

		viewHolder.tv_title.setText(listMsg.get(position).get_title());
		viewHolder.tv_content.setText(listMsg.get(position).get_content());

		// delele sms
		viewHolder.bt_delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Config cfgDel = dbHandler
						.getConfigByKeyWord(dbHandler.CFG_KW_DELETE_MSG_CHECK);

				if (cfgDel == null) {
					cfgDel = new Config(-1, 0,
							dbHandler.CFG_KW_DELETE_MSG_CHECK);

					long id = dbHandler.insertConfig(cfgDel);

					if (id > 0) {
						cfgDel.set_id((int) id);
					}
				}

				
				if(listMsg.get(position).get_title().compareTo("Sms Default") == 0){
					AlertDialog.Builder builder = new AlertDialog.Builder(
							mActivity);
					builder.setTitle("Action Deny!");
					builder.setMessage(
							"Can not delete the default messaging app !")
							.setCancelable(false)
							.setPositiveButton("Ok",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int id) {
										}
									});
					Dialog aDialog = builder.create();
					aDialog.show();
				}else if (cfgDel.get_value() == 1) {
					// delete always
					if (listMsg.size() == 1) {

						AlertDialog.Builder builder = new AlertDialog.Builder(
								mActivity);
						builder.setTitle("Action Deny!");
						builder.setMessage(
								"You must be at least 1 messages default in this section !")
								.setCancelable(false)
								.setPositiveButton("Ok",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
											}
										});
						Dialog aDialog = builder.create();
						aDialog.show();

					} else {
						dbHandler.deleteMessage(listMsg.get(position));

						if (listMsg.get(position).get_isDefault() == dbHandler.VALUE_IS_DEFAULT) {

							if (position == 0) {

								mSelectedPosition += 1;
							} else {

								mSelectedPosition -= 1;
							}

							listMsg.get(mSelectedPosition).set_isDefault(
									dbHandler.VALUE_IS_DEFAULT);
							dbHandler.updateMessage(listMsg
									.get(mSelectedPosition));
						}

						listMsg.remove(position);

						int size = listMsg.size();

						for (int i = 0; i < size; i++) {
							if (listMsg.get(i).get_isDefault() == 1) {
								mSelectedPosition = i;
							}
						}

						notifyDataSetChanged();

						((MainActivity) mActivity).updateSmsSub();
					}

				} else {
					// ask before del
					View checkBoxView = View.inflate(mContext,
							R.layout.layout_radio_button, null);
					CheckBox checkBox = (CheckBox) checkBoxView
							.findViewById(R.id.checkBox);

					checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							mIsCheck = isChecked;
						}
					});

					if (listMsg.size() == 1) {

						checkBoxView.setVisibility(View.GONE);

						AlertDialog.Builder builder = new AlertDialog.Builder(
								mActivity);
						builder.setTitle("Action Deny!");
						builder.setMessage(
								"You must be at least 1 messages default in this section !")
								.setView(checkBoxView)
								.setCancelable(false)
								.setPositiveButton("Ok",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
											}
										});
						Dialog aDialog = builder.create();
						aDialog.show();
						// delete
					} else {

						AlertDialog.Builder builder = new AlertDialog.Builder(
								mActivity);
						builder.setTitle("Warning!");
						builder.setMessage(
								"The message will be deleted after this action !")
								.setView(checkBoxView)
								.setCancelable(true)
								.setPositiveButton("Yes",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {

												dbHandler.deleteMessage(listMsg
														.get(position));

												if (listMsg.get(position)
														.get_isDefault() == dbHandler.VALUE_IS_DEFAULT) {

													if (position == 0) {

														mSelectedPosition += 1;
													} else {

														mSelectedPosition -= 1;
													}

													listMsg.get(
															mSelectedPosition)
															.set_isDefault(
																	dbHandler.VALUE_IS_DEFAULT);
													dbHandler
															.updateMessage(listMsg
																	.get(mSelectedPosition));
												}

												listMsg.remove(position);

												int size = listMsg.size();

												for (int i = 0; i < size; i++) {
													if (listMsg.get(i)
															.get_isDefault() == 1) {
														mSelectedPosition = i;
													}
												}

												notifyDataSetChanged();

												if (mIsCheck) {
													Config cfgUpdate = dbHandler
															.getConfigByKeyWord(dbHandler.CFG_KW_DELETE_MSG_CHECK);
													cfgUpdate.set_value(1);
													dbHandler
															.updateConfig(cfgUpdate);

													AlertDialog.Builder builder = new AlertDialog.Builder(
															mActivity);
													builder.setTitle("Notice!");
													builder.setMessage(
															"To restore setting go to tab setting !")
															.setCancelable(
																	true)
															.setPositiveButton(
																	"Ok",
																	new DialogInterface.OnClickListener() {
																		public void onClick(
																				DialogInterface dialog,
																				int id) {
																			
																		}

																	});
													
													Dialog aDialog = builder.create();
													aDialog.show();

												}

												((MainActivity) mActivity)
														.updateSmsSub();
											}
										})
								.setNegativeButton("No",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dialog.cancel();
											}
										});
						Dialog aDialog = builder.create();
						aDialog.show();
						// delete
					}
				}

			}
		});

		return convertView;
	}

	static class ViewHolder {

		LinearLayout ll_item_sms;
		RadioButton rad_sms_default;
		ImageButton bt_delete;
		TextView tv_title;
		TextView tv_content;

	}
}
